package com.gy.zpchat.ui.chat.base.adapter.holder;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

import im.zego.zim.callback.ZIMMediaDownloadedCallback;
import im.zego.zim.entity.ZIMCombineMessage;
import im.zego.zim.entity.ZIMCommandMessage;
//import im.zego.zim.entity.ZIMCustomMessage;
import im.zego.zim.entity.ZIMCustomMessage;
import im.zego.zim.entity.ZIMError;
import im.zego.zim.entity.ZIMMediaMessage;
import im.zego.zim.entity.ZIMMessageReaction;
import im.zego.zim.entity.ZIMMessageReactionUserInfo;
import im.zego.zim.entity.ZIMSystemMessage;
import im.zego.zim.entity.ZIMTextMessage;
import im.zego.zim.enums.ZIMMediaFileType;
import im.zego.zim.enums.ZIMMessageReceiptStatus;
import im.zego.zim.enums.ZIMMessageSentStatus;
import im.zego.zim.enums.ZIMMessageType;
import com.gy.zpchat.R;
import com.gy.zpchat.SDKManager;
import com.gy.zpchat.entity.MessageInfo;
import com.gy.zpchat.ui.chat.base.adapter.OnItemClickListener;
import com.gy.zpchat.util.UriToPathUtils;

public class BaseViewHolder extends RecyclerView.ViewHolder{

    private static final String TAG = "ChatAcceptViewHolder";
    private Activity activity;
    private final OnItemClickListener onItemClickListener;
    private RelativeLayout.LayoutParams layoutParams;
    public TextView contentTextView, userIDTextView;
    public RelativeLayout rightViewLayout;
    public LinearLayout leftViewLayout;
    private MessageInfo messageInfo;
    private ImageView imageView;
    private ImageView sentStateImageView;
    private TextView receiptStatusView;
    private ImageView fileTypeIcon;
    private ProgressBar loadingBar;

    private TextView tvReactions;
    private TextView tvTime;
    private CheckBox cbSelector;
    private ImageView avatarView;
    public BaseViewHolder(ViewGroup parent, int res, Activity activity, OnItemClickListener onItemClickListener) {
        super(LayoutInflater.from(parent.getContext()).inflate(res, parent, false));
        findViewByIds(itemView);
        this.activity = activity;
        this.onItemClickListener = onItemClickListener;
    }

    private void findViewByIds(View itemView) {
        tvReactions = itemView.findViewById(R.id.tv_reactions);
        loadingBar = itemView.findViewById(R.id.loading);
        rightViewLayout = itemView.findViewById(R.id.relativeLayout);
        leftViewLayout = itemView.findViewById(R.id.ll_chat_view);
        contentTextView = itemView.findViewById(R.id.content);
        userIDTextView = itemView.findViewById(R.id.user_id);
        sentStateImageView = itemView.findViewById(R.id.sent_state);
        imageView = itemView.findViewById(R.id.image);
        fileTypeIcon = itemView.findViewById(R.id.file_type_icon);
        receiptStatusView = itemView.findViewById(R.id.tv_receipt);
        cbSelector = itemView.findViewById(R.id.cb_select);
        tvTime = itemView.findViewById(R.id.tv_time);
        avatarView = itemView.findViewById(R.id.chat_heads);
        imageView.setOnClickListener(v -> {
            ZIMMediaMessage zimMediaMessage = (ZIMMediaMessage) v.getTag(R.id.image);
            if (zimMediaMessage != null && !"".equals(zimMediaMessage.getFileLocalPath())) {
                File file = new File(zimMediaMessage.getFileLocalPath());
                Intent intent = new Intent();
                intent.setAction(android.content.Intent.ACTION_VIEW);
                if (zimMediaMessage.getType() == ZIMMessageType.IMAGE) {
                    intent.setDataAndType(UriToPathUtils.getImageContentUri(file, activity), "image/*");
                } else if (zimMediaMessage.getType() == ZIMMessageType.VIDEO) {
                    intent.setDataAndType(UriToPathUtils.getVideoContentUri(file, activity), "video/*");
                } else if (zimMediaMessage.getType() == ZIMMessageType.AUDIO || zimMediaMessage.getType() == ZIMMessageType.FILE) {
                    //  intent.setDataAndType(UriToPathUtils.getVideoContentUri(file, activity), "*/*");
                    Toast.makeText(activity, "path:" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                    return;
                }
                activity.startActivity(intent);
            } else {
                Toast.makeText(activity, activity.getString(R.string.no_file), Toast.LENGTH_SHORT).show();
            }
        });
        if (rightViewLayout!=null){
            rightViewLayout.setOnLongClickListener(v -> {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemLongClick(messageInfo);
                }
                return true;
            });
            rightViewLayout.setOnClickListener(v -> {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(messageInfo);
                }
            });
        }
        if (leftViewLayout!=null){
            leftViewLayout.setOnLongClickListener(v -> {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemLongClick(messageInfo);
                }
                return true;
            });
            leftViewLayout.setOnClickListener(v -> {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(messageInfo);
                }
            });

        }
        cbSelector.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (onItemClickListener!=null){
                onItemClickListener.onItemSelectCheck(isChecked,messageInfo);
            }
        });
    }
    public static String stampToDate(long time) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //如果它本来就是long类型的,则不用写这一步
        Date date = new Date(time);
        res = simpleDateFormat.format(date);
        return res;
    }

    public void setMessageInfo(MessageInfo info,boolean isSelectMode,String avatar) {
        cbSelector.setVisibility(isSelectMode ?View.VISIBLE:View.GONE);
        if (isSelectMode){
            // 选择模式先置为默认
            cbSelector.setChecked(false);
        }
        if (!TextUtils.isEmpty(avatar)){
            Glide.with(activity).load(avatar).centerCrop().into(avatarView);
        }
        messageInfo = info;
        String senderUserID = messageInfo.getZIMMessage().getSenderUserID();
        userIDTextView.setText(senderUserID);
        fileTypeIcon.setVisibility(View.GONE);
        imageView.setVisibility(View.GONE);
        imageView.setBackground(null);
        imageView.setImageDrawable(null);
        contentTextView.setText("");
        tvReactions.setMovementMethod(LinkMovementMethod.getInstance());
        tvReactions.setText(getTvReactions(),TextView.BufferType.SPANNABLE);
        tvTime.setText(stampToDate(messageInfo.getZIMMessage().getTimestamp()));
        if (messageInfo.getZIMMessage().getSentStatus() == ZIMMessageSentStatus.FAILED) {
            sentStateImageView.setVisibility(View.VISIBLE);
            if (loadingBar!=null){
                loadingBar.setVisibility(View.GONE);
            }
        } else if (messageInfo.getZIMMessage().getSentStatus() == ZIMMessageSentStatus.SENDING){
            if (loadingBar !=null){
                loadingBar.setVisibility(View.VISIBLE);
            }
            sentStateImageView.setVisibility(View.GONE);
        }else {
            if (loadingBar!=null){
                loadingBar.setVisibility(View.GONE);
            }
            sentStateImageView.setVisibility(View.GONE);
        }
        if (receiptStatusView!=null){
            if (info.getZimMessageReceiptStatus() != ZIMMessageReceiptStatus.NONE){
                receiptStatusView.setVisibility(View.VISIBLE);
                if (info.getZimMessageReceiptStatus() == ZIMMessageReceiptStatus.DONE){
                    receiptStatusView.setText("✅");
                }else if (info.getZimMessageReceiptStatus() == ZIMMessageReceiptStatus.PROCESSING){
                    if (info.getReceiptUnreadMemberCount() != 0){
                        receiptStatusView.setText(String.valueOf(info.getReceiptUnreadMemberCount()));
                    }else {
                        receiptStatusView.setText("\uD83D\uDFE2");
                    }
                }else {
                    receiptStatusView.setText("❌");
                }
            }else {
                receiptStatusView.setVisibility(View.GONE);
            }
        }

        if (messageInfo.getZIMMessage().getType() == ZIMMessageType.CUSTOM){
            contentTextView.setText(String.format("[custom][%d][%s]%s",((ZIMCustomMessage) messageInfo.getZIMMessage()).subType,((ZIMCustomMessage) messageInfo.getZIMMessage()).searchedContent,Html.fromHtml(((ZIMCustomMessage) messageInfo.getZIMMessage()).message)));
        }else if (messageInfo.getZIMMessage().getType() == ZIMMessageType.TEXT) {
            contentTextView.setText(Html.fromHtml(((ZIMTextMessage) messageInfo.getZIMMessage()).message));
        }else if (messageInfo.getZIMMessage().getType() == ZIMMessageType.SYSTEM){
            contentTextView.setText(Html.fromHtml(((ZIMSystemMessage) messageInfo.getZIMMessage()).message));
        }else if (messageInfo.getZIMMessage().getType() == ZIMMessageType.COMMAND) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                contentTextView.setText("[command]: " + Html.fromHtml(new String(((ZIMCommandMessage) messageInfo.getZIMMessage()).message, StandardCharsets.UTF_8)));
            }
        } else if (messageInfo.getZIMMessage().getType() == ZIMMessageType.IMAGE || messageInfo.getZIMMessage().getType() == ZIMMessageType.VIDEO) {
            ZIMMediaMessage zimMessage = (ZIMMediaMessage) messageInfo.getZIMMessage();
            imageView.setVisibility(View.VISIBLE);
            imageView.setTag(R.id.image, messageInfo.getZIMMessage());
            if (zimMessage.getFileLocalPath() != null && !zimMessage.getFileLocalPath().equals("")) {
                if (!activity.isDestroyed()) {
                    Glide.with(activity).load(Uri.fromFile(new File(zimMessage.getFileLocalPath()))).centerCrop().into(imageView);
                }
                return;
            } else {
                SDKManager.sharedInstance().downloadMediaFile((ZIMMediaMessage) messageInfo.getZIMMessage(), ZIMMediaFileType.ORIGINAL_FILE, new ZIMMediaDownloadedCallback() {
                    @Override
                    public void onMediaDownloaded(ZIMMediaMessage message, ZIMError errorInfo) {

                        ZIMMediaMessage zimMediaMessage = (ZIMMediaMessage) imageView.getTag(R.id.image);

                        if (message.getLocalMessageID() == zimMediaMessage.getLocalMessageID()) {
                            if (!activity.isDestroyed()) {
                                imageView.setTag(R.id.image, message);
                                messageInfo.setZIMMessage(message);
                                Glide.with(activity).load(Uri.fromFile(new File(((ZIMMediaMessage) message).getFileLocalPath()))).centerCrop().into(imageView);
                            }
                        }
                    }

                    @Override
                    public void onMediaDownloadingProgress(ZIMMediaMessage message, long currentFileSize, long totalFileSize) {
//                        AppLogger.getInstance().d("[%s] [onMediaDownloadingProgress] [currentFileSize:%d, totalFileSize:%d, message: %s]", TAG, currentFileSize, currentFileSize, message.getMessageID());
                    }
                });
            }
            contentTextView.setText("");
            if (messageInfo.getZIMMessage().getType() == ZIMMessageType.VIDEO) {
                fileTypeIcon.setVisibility(View.VISIBLE);
            }
        } else if (messageInfo.getZIMMessage().getType() == ZIMMessageType.AUDIO || messageInfo.getZIMMessage().getType() == ZIMMessageType.FILE) {
            imageView.setImageResource(R.drawable.file_fill);
            imageView.setTag(R.id.image, messageInfo.getZIMMessage());
            imageView.setVisibility(View.VISIBLE);
            SDKManager.sharedInstance().downloadMediaFile((ZIMMediaMessage) messageInfo.getZIMMessage(), ZIMMediaFileType.ORIGINAL_FILE, new ZIMMediaDownloadedCallback() {

                @Override
                public void onMediaDownloaded(ZIMMediaMessage message, ZIMError errorInfo) {
                    ZIMMediaMessage zimMediaMessage = (ZIMMediaMessage) imageView.getTag(R.id.image);
                    if (message.getLocalMessageID() == zimMediaMessage.getLocalMessageID()) {
                        if (!activity.isDestroyed()) {
                            imageView.setTag(R.id.image, message);
                            messageInfo.setZIMMessage(message);
                        }
                    }
                }

                @Override
                public void onMediaDownloadingProgress(ZIMMediaMessage message, long currentFileSize, long totalFileSize) {
//                    AppLogger.getInstance().d("[%s] [onMediaDownloadingProgress] [currentFileSize:%d, totalFileSize:%d, message: %s]", TAG, currentFileSize, currentFileSize, message.getMessageID());
                }
            });
        }else if (messageInfo.getZIMMessage().getType() == ZIMMessageType.COMBINE){
            ZIMCombineMessage message = (ZIMCombineMessage) messageInfo.getZIMMessage();
            contentTextView.setText(String.format("%s \n ---------------- \n %s",message.title,message.summary));
        }
    }

    private SpannableStringBuilder getTvReactions() {
        SpannableStringBuilder ssb = new SpannableStringBuilder();
        for (ZIMMessageReaction messageReaction : messageInfo.getMessageReactions()) {
            StringBuilder reaction = new StringBuilder(messageReaction.reactionType);
            reaction.append("(");
            reaction.append(messageReaction.totalCount);
            reaction.append("):");
            for (ZIMMessageReactionUserInfo userInfo : messageReaction.userList) {
                reaction.append(userInfo.userID);
                reaction.append(",");
            }
            ssb.append(reaction.toString());

            ssb.append("\t");
            int start = Math.max(ssb.toString().indexOf(messageReaction.reactionType),0);
            ssb.setSpan(new ClickableSpan() {
                @Override
                public void onClick(@NonNull View widget) {
                    if (onItemClickListener !=null){
                        onItemClickListener.onItemReactionClick(messageReaction.reactionType,messageInfo);
                    }
                }

                @Override
                public void updateDrawState(@NonNull TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setColor(Color.BLUE);
                    ds.setUnderlineText(false);
                }
            },start,start+reaction.length(),0);
        }
        return ssb;
    }

    public void release() {
        if (imageView != null) {
            imageView.setOnClickListener(null);
        }
        if (rightViewLayout != null) {
            rightViewLayout.setOnLongClickListener(null);
        }
        activity = null;
    }

}
